package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.ContentConfig;
import com.example.forum.model.User;
import com.example.forum.service.imp.UserServiceImp;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.UUIDUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServiceImp userService;

    /**
     * 注册
     * @param username
     * @param nickname
     * @param password
     * @param passwordRepeat
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/register")
    //这里可以使用@notnull进行数据非空校验
    public AppResult register(@RequestParam(value = "username") String username,
                              @RequestParam(value = "nickname") String nickname,
                              @RequestParam(value = "password") String password,
                              @RequestParam(value = "passwordRepeat") String passwordRepeat){

        //进行非空的校验
        if(!StringUtils.hasLength(username)
        ||!StringUtils.hasLength(nickname)
        ||!StringUtils.hasLength(passwordRepeat)
        ||!StringUtils.hasLength(password)){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //对于基本信息的赋值操作，传递给service层
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        //user.setPassword(password);这里插入的是属于MD5加密的密码

        //进行重复输入密码的判断
        if(!password.equals(passwordRepeat)){
            //两次输入的密码不相等
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }


        //随机生成的盐
        String salt = UUIDUtil.uuid_32();

        //进行MD5加密的操作
        String ciphertext = MD5Util.md5Salt(password,salt);
        //放置用户对象中
        user.setPassword(ciphertext);
        //盐也要存入到对象中
        user.setSalt(salt);

        //最后写入数据库，并返回数据
        userService.createNormalUser(user);
        return AppResult.success();
    }

    /**
     * 登录
     * @param request
     * @param username
     * @param password
     * @return
     */

    @RequestMapping(method = RequestMethod.POST,value = "/login")
    public AppResult login(HttpServletRequest request,
                           @RequestParam(value = "username") @NonNull String username,
                           @RequestParam(value = "password") @NonNull String password){
        User user = userService.login(username,password);
        //设置HTTPsession会话，没有会话设置会话

        HttpSession session = request.getSession(true);
        //保存到session中
        session.setAttribute(ContentConfig.USER_SESSION,user);

        return AppResult.success();
    }

    /**
     * 获取用户中心信息
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(method = RequestMethod.GET,value = "/info")
    public AppResult<User> getUserinfo(HttpServletRequest request,
                                       @RequestParam(value = "id",required = false) Long id){
        User user = null;
        if(id == null){
            HttpSession session = request.getSession(true);
            //判断用户是否进行了登录
            if(session == null || session.getAttribute(ContentConfig.USER_SESSION ) == null){
                return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
            }
            user =(User) session.getAttribute(ContentConfig.USER_SESSION);
        }else {
             user = userService.selectById(id);
        }
        if(user == null){
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    /**
     * 用户进行退出的操作
     * @return
     */
    @RequestMapping(value = "/logout" ,method = RequestMethod.GET)
    public AppResult logout(HttpServletRequest request){
        //这里执行的就是session的删除的操作
        HttpSession session = request.getSession(false);
        if(session != null){
            //session的注销的操作
            session.invalidate();
        }

        return AppResult.success();

    }

    @PostMapping("/modifyInfo")
    public AppResult modifyInfo (HttpServletRequest request,
                                @RequestParam(value = "username",required = false) String username,
                                @RequestParam(value = "nickname",required = false) String nickname,
                                @RequestParam(value = "gender",required = false) Byte gender,
                                @RequestParam(value = "email",required = false) String email,
                                @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @RequestParam(value = "remark",required = false) String remark) {
        if(username == null && nickname == null && gender == null && email == null && phoneNum == null && remark == null){
            return AppResult.fail("请输入要修改的内容");
        }


        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(ContentConfig.USER_SESSION);

        //这里要进行id的构造，需要传输这里的id
        User updateUser = new User();

        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        userService.modifyInfo(updateUser);
        //再次查询最新的user
        User newUser =  userService.selectById(user.getId());
        //传入到session中
        session.setAttribute(ContentConfig.USER_SESSION,newUser);

        return AppResult.success(newUser);
    }
    @RequestMapping("modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                  @RequestParam("oldPassword") @NonNull String oldPassword,
                                  @RequestParam("newPassword") @NonNull String newPassword,
                                  @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 1. 校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)) {
            // 返回错误描述
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 2. 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(ContentConfig.USER_SESSION);
        // 3. 调用Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        // 4. 销毁session
        if (session != null) {
            session.invalidate();
        }
        // 5. 返回结果
        return AppResult.success();
    }

    @GetMapping("/otherInfo")
    public ResponseEntity<Map<String, Object>> getUserInfo(@RequestParam("userId") Long userId) {
        User user = userService.selectById(userId);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 0);
        response.put("data", user);
        return ResponseEntity.ok(response);
    }
}
